import { deleteCart, getCartList, updateCart } from '@/api/cart'
import { Toast } from 'vant'

export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  mutations: {
    setCartList (state, newList) {
      newList.forEach(item => {
        item.isChecked = true
      })
      state.list = newList
      // console.log(newList)
    },
    toggleCheck (state, goodsId) {
      const goods = state.list.find(item => item.goods_id === goodsId)
      goods.isChecked = !goods.isChecked
    },
    toggleAllCheck (state, flag) {
      state.list.forEach(item => {
        item.isChecked = flag
      })
    },
    changeCount (state, { goodsId, value }) {
      const obj = state.list.find(item => item.goods_id === goodsId)
      obj.goods_num = value
    }
  },
  actions: {
    async getCartList (context) {
      const res = await getCartList()
      // console.log(res.data.list)
      context.commit('setCartList', res.data.list)
    },
    async changeCountAction (context, obj) {
      const { goodsId, value, skuId } = obj
      context.commit('changeCount', {
        goodsId,
        value
      })
      await updateCart(goodsId, value, skuId)
    },
    async deleteAction (context) {
      const arr = context.getters.getCheckedList
      const res = await deleteCart(arr.map(item => item.id))
      await context.dispatch('getCartList')
      if (res.status === 200) Toast.success('删除成功!')
    }
  },
  getters: {
    getTotalCount (state) {
      let total = 0
      state.list.forEach(item => {
        total += item.goods_num
      })
      return total
    },
    getCheckedCount (state) {
      let total = 0
      state.list.forEach(item => {
        if (item.isChecked) {
          total += item.goods_num
        }
      })
      return total
    },
    getTotalPrice (state) {
      let total = 0
      state.list.forEach(item => {
        if (item.isChecked) {
          total += +item.goods.goods_price_min * item.goods_num
        }
      })
      return total
    },
    isAllChecked (state) {
      return state.list.every(item => item.isChecked)
    },
    getCheckedList (state) {
      return state.list.filter(item => item.isChecked)
    },
    getCheckedId (state) {
      return state.list.filter(item => item.isChecked).map(item => item.id)
    }
  }
}
